<?php


require_once 'Lib/Config/Config.php';
require_once 'Lib/CallerService.php';
require_once 'Common/NVP_SampleConstants.php';
require_once 'Common/DB.php';

session_start();
//$num=5;
$price=4.3;

$db = DbCon::getInstance();
$connect = $db->getCon();

//获取当前订单人数
$sql_order="select count(*) as num from `order` where pid=1 and type <3 and flag =1";
$orders=mysql_query($sql_order,$connect);

$line = mysql_fetch_row($orders);

$num=$line[0];
//插入用户资料
$sql="insert into tmp set add_time=now(),pid=1,address='test address',email='test@iobit.com'";
$sql.=",fname='test',lname='test',status='checking'";
mysql_query($sql,$connect);

//获得临时订单id
$id=mysql_insert_id();

if($num<40)
{
	$method="";
	$serverName = $_SERVER['SERVER_NAME'];
	$serverPort = $_SERVER['SERVER_PORT'];
	$url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);


	$returnURL = $url;
	$cancelURL = $url;
	$request_array = array (
		Preapproval::$cancelUrl => $cancelURL,
		Preapproval::$returnUrl => $returnURL,
		Preapproval::$currencyCode => 'USD',
		Preapproval::$startingDate => date('Y-m-d'),
		Preapproval::$ipnNotificationUrl => $url.'/notify.php?id='.$id."&pid=1",
		Preapproval::$endingDate =>  date('Y-m-d',time()+3600*24*2),
		Preapproval::$maxNumberOfPayments => 1,
		Preapproval::$maxTotalAmountOfAllPayments => $price,
		Preapproval::$requestEnvelope_senderEmail =>  '',
		RequestEnvelope::$requestEnvelopeErrorLanguage => 'en_US'
	);

	$nvpStr=http_build_query($request_array, '', '&');
	$resArray=hash_call("AdaptivePayments/Preapproval",$nvpStr);

	$ack = strtoupper($resArray['responseEnvelope.ack']);
	
	if($ack!="SUCCESS")
	{
		$_SESSION['reshash']=$resArray;
		$location = "AdaptivePayments/APIError.php";
		header("Location: $location");
	}
	else
	{
		//把返回的key写入零时表
		$sql_upt="update tmp set updatetime=now(),`type`=1, `key`='".$resArray['preapprovalKey']."' where id=".$id;
		mysql_query($sql_upt,$connect);
		$db->closeDB();
		$_SESSION['key'] = $resArray['preapprovalKey'];
		$payPalURL = PAYPAL_REDIRECT_URL.'_ap-preapproval&preapprovalkey='.$resArray['preapprovalKey'];
		header("Location:".$payPalURL);
	}
}
else
{
	//直接提交
	
	$serverName = $_SERVER['SERVER_NAME'];
	$serverPort = $_SERVER['SERVER_PORT'];
	
	$url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);
	
	$returnURL = $url;
	$cancelURL = $url ;
	$request_array= array(
		Pay::$actionType => 'PAY',
		Pay::$cancelUrl  => $cancelURL,
		Pay::$returnUrl=>   $returnURL,
		Pay::$currencyCode  => 'USD',
	
		Pay::$clientDetails_deviceId  => DEVICE_ID,
		Pay::$clientDetails_ipAddress  => '127.0.0.1',
		Pay::$clientDetails_applicationId =>APPLICATION_ID,
		Pay::$ipnNotificationUrl => $url.'/notify.php?id='.$id."&pid=1",
		RequestEnvelope::$requestEnvelopeErrorLanguage => 'en_US',
		Pay::$memo => "test",
		//Pay::$feesPayer => "PRIMARYRECEIVER",
		Pay::$receiverEmail[0] => "david_1314930816_biz@163.com",
		Pay::$receiverAmount[0] => $price,
	);
	
	
	$nvpStr=http_build_query($request_array, '', '&');

	/* Make the call to PayPal to get the Pay token
	 If the API call succeded, then redirect the buyer to PayPal
	 to begin to authorize payment.  If an error occured, show the
	 resulting errors
	 */

	$resArray=hash_call('AdaptivePayments/Pay',$nvpStr);
	
	//print_r($resArray);exit;
	/* Display the API response back to the browser.
	 If the response from PayPal was a success, display the response parameters'
	 If the response was an error, display the errors received using APIError.php.
	 */
	$ack = strtoupper($resArray['responseEnvelope.ack']);

	if($ack!="SUCCESS"){
		$_SESSION['reshash']=$resArray;
		$location = "AdaptivePayments/APIError.php";
		header("Location: $location");
	}
	else
	{
		//把获取的paykey更新到tmp表里面
		$sql_upt="update tmp set updatetime=now(),`type`=2, `key`='".$resArray['payKey']."' where id=".$id;
		mysql_query($sql_upt,$connect);
		$db->closeDB();
		$_SESSION['key'] = $resArray['payKey'];
		$payKey=$resArray['payKey'];
		header('Location:'.PAYPAL_REDIRECT_URL.'_ap-payment&paykey='.$payKey);
		exit;
	}
	 
}

